/*    Copyright 2010 Tobias Marschall
 *
 *    This file is part of MoSDi.
 *
 *    MoSDi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    MoSDi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with MoSDi.  If not, see <http://www.gnu.org/licenses/>.
 */

package mosdi.tests;

import static org.junit.Assert.assertEquals;

import java.io.File;

import mosdi.fa.Alphabet;
import mosdi.fa.IIDTextModel;

import org.junit.Test;

public class IIDTextModelTest {

   @Test
   public void testReadFromAndWriteToFile() {
      File testFile = new File("testFile"+System.currentTimeMillis());
      if (testFile.exists()) {
         System.err.printf("Sorry, the file '%s' already exists.%n Abort test.", testFile);
         return;
      }
      
      Alphabet alphabet = Alphabet.getDnaAlphabet();
      IIDTextModel model = new IIDTextModel(alphabet.size());
      model.writeToFile(testFile, alphabet);
      IIDTextModel model2 = IIDTextModel.readFromFile(testFile.getPath(), alphabet);
      testModelEquality(model, model2, 0.0000000000000000000000001);
      testFile.delete();
      
      alphabet = Alphabet.getIupacAlphabet();
      model = new IIDTextModel(alphabet.size());
      model.writeToFile(testFile, alphabet);
      model2 = IIDTextModel.readFromFile(testFile.getPath(), alphabet);
      testModelEquality(model, model2, 0.0000000000000001);
      testFile.delete();
      
      model = new IIDTextModel(alphabet, "THMRBBKBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBMRTHGBRMNNNWHRBSGWNNRAWSTHBVWDWHKRDKNSTRKMHBCSWGSHCMANHHHHHHHTAKTKHNBWCDMCVADDVVDCNNNNTTTTGCWTGMBNRDDDDDDDDDDDDDYSRVMDBNNDK");
      model.writeToFile(testFile, alphabet);
      model2 = IIDTextModel.readFromFile(testFile.getPath(), alphabet);
      testModelEquality(model, model2, 0.000001);
      testFile.delete();
      
   }

   private static void testModelEquality(IIDTextModel model, IIDTextModel model2, double epsilon) {
      assertEquals(model.getCharacterDistribution().length, model2.getCharacterDistribution().length);
      for (int i = 0; i < model.getCharacterDistribution().length; ++i) {
         assertEquals(model.getCharacterDistribution()[i], model2.getCharacterDistribution()[i], epsilon);
      }
      assertEquals(model.getAlphabetSize(), model2.getAlphabetSize());
   }

}
